﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Helpers;
using Infrastructure.Data;
using Keepo.Models;

namespace AlbumDesigner.Helpers
{
    //this Attribute will be executed for each user's request
    public class SaveLastLoginAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var Request = filterContext.HttpContext.Request;
            var Response = filterContext.HttpContext.Response;
            var Action = filterContext.RouteData.Values["action"].ToString();

            if (Action != "IsUserSleeping")
            {
                if (UserHelper.IsLogon())
                {
                    var userId = UserHelper.CurrentUser().UserId;

                    //save the last ip and last login date of this user
                    using (GenericRepository repository = new GenericRepository())
                    {
                        var existUser = repository.GetByKey<User>(userId);
                        existUser.LastLogin = DateTime.Now;
                        existUser.LastIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                        repository.UnitOfWork.SaveChanges();
                    }
                }
            }
        }
    }
}